package com.zbkj.crmeb.supplier.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.pac.sdk.cp.dataobject.response.MODUAN_ORDER_CREATE.response;
import com.zbkj.crmeb.chant.dto.ApplyAuditAndSupplierDTO;
import com.zbkj.crmeb.chant.dto.ChannelMerchantSupplierDTO;
import com.zbkj.crmeb.chant.model.ChannelDiscountPackage;
import com.zbkj.crmeb.chant.model.ChannelMemberLevel;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelMerchantExperience;
import com.zbkj.crmeb.chant.request.MerchantListRequest;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.vo.ChannelMerchantVO;
import com.zbkj.crmeb.enums.BusinessApplyCodeEnum;
import com.zbkj.crmeb.enums.SupplierTypeEnum;
import com.zbkj.crmeb.enums.WineryAuditStatusEnum;
import com.zbkj.crmeb.enums.WineryShippingTypeEnum;
import com.zbkj.crmeb.store.request.BusinessApplyRequest;
import com.zbkj.crmeb.store.request.SupplierOpenShopProductRequest;
import com.zbkj.crmeb.store.response.BusinessApplyResponse;
import com.zbkj.crmeb.store.response.CustomsRecordResponse;
import com.zbkj.crmeb.store.response.SupplierOpenShopProductResponse;
import com.zbkj.crmeb.supplier.dao.BusinessApplyDao;
import com.zbkj.crmeb.supplier.dao.SupplierOpenShopProductDao;
import com.zbkj.crmeb.supplier.model.BusinessApply;
import com.zbkj.crmeb.supplier.model.SupplierOpenShopProduct;
import com.zbkj.crmeb.supplier.service.BusinessApplyService;
import com.zbkj.crmeb.user.model.User;


@Service("businessApplyService")
public class BusinessApplyServiceImpl extends ServiceImpl<BusinessApplyDao, BusinessApply> implements BusinessApplyService {

    @Resource
    private BusinessApplyDao businessApplyDao;
    @Resource
    private IChannelMerchantService channelMerchantService;

    private static final Logger logger = LoggerFactory.getLogger(BusinessApplyServiceImpl.class);

    /**
     * 列表
     * @param request 请求参数
     * @param pageParamRequest 分页类参数
     * @author Mr.Zhang
     * @since 2020-05-27
     * @return List<StoreProduct>
     */
    @Override
    public PageInfo<BusinessApplyResponse> getList(BusinessApplyRequest request, PageParamRequest pageParamRequest) {
        //条件查询
        Page<BusinessApply> businessApplyPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<BusinessApplyResponse> businessApplys = businessApplyDao.queryList(request);

        if(CollectionUtils.isEmpty(businessApplys)) {
            return CommonPage.copyPageInfo(businessApplyPage, new ArrayList<>());
        }
        List<Integer> merIdList = businessApplys.stream().map(BusinessApplyResponse::getMerId).distinct().collect(Collectors.toList());
        List<ChannelMerchant> channelMerchantList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery()
                .in(ChannelMerchant::getId, merIdList));;
        Map<Integer, String> channelMerchantMap = channelMerchantList.stream().collect(Collectors.toMap(ChannelMerchant::getId, ChannelMerchant::getChannelName, (e1, e2) -> e2));

        businessApplys.forEach(e -> {
            Integer type = e.getShippingType();
            if(null != type){
                String name = WineryShippingTypeEnum.getMsgByCode(type);
                e.setShippingTypeName(name);
            }
            Integer merId = e.getMerId();
            if(null != merId){
                String name2 = channelMerchantMap.get(merId);
                if (null != name2) {
                    e.setChannelName(name2);
                }
            }
            Integer applyType = e.getApplyType();
            if(null != applyType){
                SupplierTypeEnum typeEnum = SupplierTypeEnum.getTypeByCode(applyType);
                e.setApplyTypeName(typeEnum.getTypeName());
            }
        });
        return CommonPage.copyPageInfo(businessApplyPage, businessApplys);
    }

    /**
     * 审核通过并添加渠道供应商
     *
     * @param entity
     * @author daigb
     * @date: 2022-03-18 14:23
     */
    @Override
    public CommonResult<String> businessApplyAudit(ApplyAuditAndSupplierDTO entity) {
        Integer auditStatus = entity.getAuditStatus();
        Integer id = entity.getId();
        if(null == auditStatus || null == id){
            throw new CrmebException("参数错误!");
        }
        if(WineryAuditStatusEnum.REJECT.getCode().equals(auditStatus)){
            String rejectReason = entity.getRejectReason();
            LambdaUpdateWrapper<BusinessApply> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

            lambdaUpdateWrapper.eq(BusinessApply::getId, id);
            if(StringUtils.isNotBlank(rejectReason)){
                lambdaUpdateWrapper.set(BusinessApply::getRejectReason, rejectReason);
            }

            lambdaUpdateWrapper.set(BusinessApply::getAuditStatus, auditStatus);

            if(update(lambdaUpdateWrapper)){
                return CommonResult.success();
            }else {
                return CommonResult.failed();
            }
        }else if(WineryAuditStatusEnum.APPROVE.getCode().equals(auditStatus)){
            LambdaUpdateWrapper<BusinessApply> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

            lambdaUpdateWrapper.eq(BusinessApply::getId, id);
            lambdaUpdateWrapper.set(BusinessApply::getAuditStatus, auditStatus);

            boolean res = update(lambdaUpdateWrapper);
            if(res){
                // 添加供应商
                entity.setSource(BusinessApplyCodeEnum.WINERY.getName());
                entity.setApplyId(id);
                ChannelMerchantSupplierDTO dto = new ChannelMerchantSupplierDTO();
                BeanUtils.copyProperties(entity, dto);
                return channelMerchantService.addMerchantSupplier(dto);
            }else {
                return CommonResult.failed();
            }
        }
        return CommonResult.failed();
    }

}